from lib.base.notifier import baseStnNotifier
from lib.utils.utils import *

import smtplib
from email.mime.text import MIMEText
from email.header import Header

class gmailStnNotifier(baseStnNotifier):
    SMTP_GMAIL_SERVER = 'smtp.gmail.com:587'
    
    def run(self):
        # init param with default value or from config file
        type = self.jsonCfg.evalGet(self.notify, 'type', 'notify')
        toaddr = self.jsonCfg.evalGet(self.notify, 'to')
        fromaddr = self.jsonCfg.evalGet(self.notify, 'from')
        username = self.jsonCfg.evalGet(self.notify, 'username')
        password = self.jsonCfg.evalGet(self.notify, 'password')
        subject = self.jsonCfg.evalGet(self.notify, 'subject')
        body = self.jsonCfg.evalGet(self.notify, 'body')
        
        self.logger.log(logging.DEBUG_01,"type: %s, to: %s, from: %s, username: %s, password: %s, subject: %s, body: %s)" 
                          % (type, toaddr, fromaddr, username, password, subject, body))
        
        # call real trigger function
        return self.__notify(toaddr, fromaddr, username, password, subject, body)
        
    def __notify(self, toaddr, fromaddr, username, password, subject, body):    
        # get and format params (interpolate with buffer)
        toaddr = toaddr.format(*self.buffer)
        fromaddr = fromaddr.format(*self.buffer)
        subject = subject.format(*self.buffer)
        body = body.format(*self.buffer)
        
        # Create a text/plain message
        msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
        
        msg['To'] = toaddr
        msg['From'] = fromaddr
        msg['Subject'] = Header(subject, 'utf-8')
        
        # Send mail  
        try:
            server = smtplib.SMTP(self.SMTP_GMAIL_SERVER)  
            server.starttls()  
            server.login(username, password)  
            server.sendmail(fromaddr, toaddr, msg.as_string())  
            server.quit()
            self.logger.info("Mail sended with gmail to: %s" % toaddr) 
        except smtplib.SMTPException as e:
            self.logger.error("Can't send mail: (%s) %s" % (e.smtp_code, e.smtp_error))
            return False
        
        return True
        
        